init("0", 2)
luaExitIfCall(true)

function getScreenType()
    SCREEN_HEIGHT, SCREEN_WIDTH = getScreenSize()
    local k = SCREEN_WIDTH / SCREEN_HEIGHT
    if math.abs(k - 3 / 2) < 0.01 then
        return "3_2"
    elseif math.abs(k - 16 / 9) < 0.01 then
        return "16_9"
    elseif math.abs(k - 4 / 3) < 0.01 then
        return "4_3"
    end
end

-- --------------初始化常量--------------------------
DEVICE_TYPE, SCREEN_TYPE, DEVICE_ID, TS_VER, OS_VER = getDeviceType(), getScreenType(), getDeviceID(), getTSVer(), getOSVer()
SCREEN_HEIGHT, SCREEN_WIDTH = getScreenSize()
COCAPP_IDENTIFIER = "com.supercell.magic"
buttonWidth, buttonHeight = 0.0757 * SCREEN_WIDTH, 0.159 * SCREEN_HEIGHT
-- --------------初始化常量--------------------------

function ts_frontapp()
    front_app = frontAppBid();
    if front_app ~= COCAPP_IDENTIFIER then
        return false;
    else
        return true;
    end
end

function touchDU(x, y)
    if ts_frontapp() == false then
        return
    end


    touchDown(1, x, y)
    mSleep(50)
    touchUp(1, x, y)
    mSleep(50)
end

function cordFromTouch5(x, y)
    return SCREEN_WIDTH * x / 1136, SCREEN_HEIGHT * y / 640
end

function cordFromiPadMini2(x, y)
    return SCREEN_WIDTH * x / 2048, SCREEN_HEIGHT * y / 1536
end

function cordFromiPhone4(x, y)
    return SCREEN_WIDTH * x / 960, SCREEN_HEIGHT * y / 640
end

function is_sameColor(r1, g1, b1, r2, g2, b2)
    return math.abs(r1 - r2) < 20 and math.abs(g1 - g2) < 20 and math.abs(b1 - b2) < 20
end


function getRealCord(key)
    if DEVICE_TYPE <= 1 then
        -- iTouch And iPhone
        local rawx, rawy, r, g, b = conf_16_9[key][1], conf_16_9[key][2], conf_16_9[key][3], conf_16_9[key][4], conf_16_9[key][5]
        local x, y = cordFromTouch5(rawx, rawy)
        return x, y, r, g, b
    else
        -- iPad
        return 0, 0, 0, 0, 0
    end
end


function is_okayColorForPointWithKey(key)
    local x, y, r, g, b = getRealCord(key)
    local realR, realG, realB = getColorRGB(x, y)
    return is_sameColor(r, g, b, realR, realG, realB)
end

function is_okayColorForPointWithRGB(x, y, r, g, b)
    local realR, realG, realB = getColorRGB(x, y)
    return is_sameColor(r, g, b, realR, realG, realB)
end

-- -------------各种动作-----------------
-- 根据key来点击,跳过颜色检查
function touchButtonForKeySkipCheckClor(key)
    local x, y, r, g, b = getRealCord(key)
    touchDU(x, y)
end

-- 根据key来点击,并且检查颜色
function touchButtonForKey(key)
    local x, y, r, g, b = getRealCord(key)
    if is_okayColorForPointWithKey(key) then
        touchDU(x, y)
        return true
    end

    return false
end

-- 缩小地图small
function smallShrink()
    touchDU(10, 10)

    number = 5
    touchDown(1, SCREEN_WIDTH / number, SCREEN_HEIGHT / 2)
    touchDown(2, SCREEN_WIDTH * (number - 1) / number, SCREEN_HEIGHT / 2)
    mSleep(50)

    for i = 1, 400, 50 do
        touchMove(1, SCREEN_WIDTH / number + i, SCREEN_HEIGHT / 2)
        touchMove(2, SCREEN_WIDTH * (number - 1) / number - i, SCREEN_HEIGHT / 2)
        mSleep(50)
    end

    touchUp(1, SCREEN_WIDTH / number + 400, SCREEN_HEIGHT / 2)
    touchUp(2, SCREEN_WIDTH * (number - 1) / number - 400, SCREEN_HEIGHT / 2)

    mSleep(200)
end

-- 缩小地图
function shrink()
    smallShrink()
    smallShrink()
end


-- 地图上移
function moveUp()
    touchDown(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)
    mSleep(50)
    for i = 1, SCREEN_HEIGHT / 2, 50 do
        touchMove(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4 + i)
        mSleep(50)
    end
    touchUp(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3 / 4)

    mSleep(200)
end



-- 地图下移
function moveDown()
    touchDown(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3 / 4)
    mSleep(50)
    for i = 1, SCREEN_HEIGHT / 2, 50 do
        touchMove(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4 - i)
        mSleep(50)
    end
    touchUp(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)

    mSleep(200)
end

-- 回到主屏幕
function backToHome()
    if is_clanWarPage() then
        touchButtonForKeySkipCheckClor("returnHomeButton")
    end

    if is_donateOpen() then
        touchButtonForKey("donate_1", false)
    end

    touchButtonForKeySkipCheckClor("rightTopCorner", true)

    shrink()
    moveUp()
end


-- 出发干仗
function goBattle()
    backToHome()
    if touchButtonForKey("attackbutton") == false then
        return
    end
    if touchButtonForKey("findMatchButton") == false then
        return
    end
    touchButtonForKey("confirmGo")
end

-- 根据位置造兵
function trainDependsOnKey(key)
    for i = 1, 76, 1 do
        touchButtonForKey(key)
    end
end

-- 根据兵营的次序造兵
function trainDependsOnNumber(num)
    -- 1 弓箭, 2 胖子, 3 黄人, 4 胖子
    if num == 1 then
        trainDependsOnKey("trainAnchor")
    elseif num == 2 then
        trainDependsOnKey("trainGiant")
    elseif num == 3 then
        trainDependsOnKey("trainBarbarian")
    elseif num == 4 then
        trainDependsOnKey("trainGiant")
    end
end

-- 造兵
function trainSoldier()

    backToHome()

    touchButtonForKeySkipCheckClor("rightDownBarracks")

    if touchButtonForKey("trainSword") == false then
        return
    end

    local number = 0
    for i = 1, 8, 1 do
        if is_barracksTraining() then
            number = number + 1
            trainDependsOnNumber(number)
        end
        -- 切换
        if touchButtonForKey("barracks_1") == false then
            return
        end
    end
end

-- -------------各种动作-----------------

-- --------------sbAttack---------------
-- --------------sbAttack初始化----------

sbattack_conf = {
    ["3_2"] = {
        ["troop_button_width"] = 0.0896 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.167 * SCREEN_HEIGHT,
        ["request_troop_startX"] = 40,
        ["request_troop_startY"] = 231,
        ["request_troop_width"] = math.floor(0.5 + SCREEN_WIDTH * 0.0385),
        ["request_troop_height"] = math.floor(0.5 + SCREEN_HEIGHT * 0.0297),
        ["set_troop_startX"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.403 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.276 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.266 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.357 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.364 * SCREEN_HEIGHT,
    },
    ["16_9"] = {
        ["troop_button_startX"] = 0.0855 * SCREEN_WIDTH,
        ["troop_button_startY"] = 0.824 * SCREEN_HEIGHT,
        ["troop_button_width"] = 0.0757 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.159 * SCREEN_HEIGHT,
        ["request_troop_startX"] = 40,
        ["request_troop_startY"] = 231,
        ["request_troop_width"] = math.floor(0.5 + SCREEN_WIDTH * 0.0317),
        ["request_troop_height"] = math.floor(0.5 + SCREEN_HEIGHT * 0.0297),
        ["set_troop_startX"] = 0.2 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.375 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.4 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.15 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.3 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.26 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.38 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.38 * SCREEN_HEIGHT,
    },
    ["4_3"] = {
        ["troop_button_width"] = 0.084 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.1374 * SCREEN_HEIGHT,
        ["request_troop_startX"] = 82,
        ["request_troop_startY"] = 348,
        ["request_troop_width"] = math.floor(0.5 + SCREEN_WIDTH * 0.0269),
        ["request_troop_height"] = math.floor(0.5 + SCREEN_HEIGHT * 0.0182),
        ["set_troop_startX"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.403 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.2866 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.2337 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.37 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.32 * SCREEN_HEIGHT,
    },
}
sbattack_vars = sbattack_conf[SCREEN_TYPE]
buttonWidth, buttonHeight = sbattack_vars["troop_button_width"], sbattack_vars["troop_button_height"]

BUTTON_POSITIONS = {}
TROOPS_COLORS = {
    ["barbarian"] = {{0.07865, 0.67924, 255, 203, 181}, {0.49456, 0.21802, 255, 247, 49}, {0.54407, 0.35220, 255, 199, 33}},
    ["archer"] = {{0.14813, 0.41928, 140, 40, 82}, {0.49472, 0.26834, 255, 97, 206}, {0.66306, 0.41928, 255, 65, 123}},
    ["goblin"] = {{0.08887, 0.58700, 99, 36, 8}, {0.48498, 0.32704, 181, 247, 107}, {0.72264, 0.36058, 189, 247, 99}},
    ["gaint"] = {{0.32670, 0.41928, 255, 138, 16}, {0.61387, 0.34381, 255, 215, 156}, {0.81192, 0.88050, 165, 105, 99}},
    ["wallbreaker"] = {{0.17832, 0.57861, 82, 65, 66}, {0.58432, 0.64570, 255, 231, 214}, {0.67345, 0.39412, 231, 134, 74}},
    ["king"] = {{0.23805, 0.55345, 222, 190, 90}, {0.47572, 0.56184, 255, 199, 189}, {0.73318, 0.87211, 198, 60, 74}},
    ["queen"] = {{0.31744, 0.28511, 156, 65, 255}, {0.74325, 0.41928, 57, 28, 107}, {0.54520, 0.77148, 132, 138, 82}},
    ["ragespell"] = {{0.46614, 0.31865, 247, 174, 132}, {0.42652, 0.61215, 66, 32, 107}, {0.58497, 0.81341, 214, 109, 247}}
}

function getTroopParam(troopType, dx, dy)
    local troopColors = TROOPS_COLORS[troopType]
    local param = dx .. "|0|" .. string.format("0x%06X", troopColors[2]) .. ",0|" .. dy .. "|" .. string.format("0x%06X", troopColors[3]) .. "," .. dx .. "|" .. dy .. "|" .. string.format("0x%06X", troopColors[4])
    return string.format("0x%06X", troopColors[1]), param
end

function findFirstTroopButtonPosition()
    local dx, dy = math.floor(0.5 + buttonWidth / 4), math.floor(0.5 + buttonHeight / 4)
    local startX, startY, endX, endY = 0, (SCREEN_HEIGHT - buttonHeight * 2), SCREEN_WIDTH / 3, SCREEN_HEIGHT
    mSleep(1000)
    local color, param = getTroopParam("barbarian", dx, dy)
    local tmpX, tmpY = findMultiColorInRegionFuzzy(color, param, 90, startX, startY, endX, endY)
    if tmpX ~= -1 and tmpY ~= -1 then
        return tmpX - dx, tmpY - dy
    end
    return -1, -1
end

function findTroopButtonKind(x, y)
    local dx, dy = math.floor(0.5 + buttonWidth / 4), math.floor(0.5 + buttonHeight / 4)
    for troopType, colors in pairs(TROOPS_COLORS) do
        local troopColors = TROOPS_COLORS[troopType]
        local ok = true
        for i = 1, 3 do
            local tmpX, tmpY, r, g, b = math.floor(0.5 + x + troopColors[i][1] * buttonWidth), math.floor(0.5 + y + troopColors[i][2] * buttonHeight), troopColors[i][3], troopColors[i][4], troopColors[i][5]
            if is_okayColorForPointWithRGB(tmpX, tmpY, r, g, b) == false then
                ok = false
            end
        end
        if ok then
            return troopType
        end
    end
    return -1
end

function setTroopButtonsPosition()
    local startX, startY = sbattack_vars["troop_button_startX"], sbattack_vars["troop_button_startY"]
    for i = 1, 11 do
        local x = startX + (i - 1) * buttonWidth
        local troopType = findTroopButtonKind(math.floor(0.5 + x), math.floor(0.5 + startY), math.floor(0.5 + x + buttonWidth), math.floor(0.5 + startY + buttonHeight))
        local otherIndex = 1
        wLog("test", troopType)
        if troopType ~= -1 then
            BUTTON_POSITIONS[troopType] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
        elseif BUTTON_POSITIONS["castle"] == nil then
            BUTTON_POSITIONS["castle"] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
        else
            BUTTON_POSITIONS["other"..otherIndex] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
            otherIndex = otherIndex + 1
        end
    end
end

function setTroops(troopType, count, startX, startY, endX, endY)
    local dx, dy = (endX - startX) / (count - 1), (endY - startY) / (count - 1)
    local postion = BUTTON_POSITIONS[troopType]
    if postion == nil then
        return
    end
    local troopButtonX, troopButtonY = postion[1], postion[2]

    if troopButtonX > 0 and troopButtonY > 0 then
        touchDU(troopButtonX, troopButtonY)
        local x, y = -1, -1
        for i = 1, count do
            x = startX + dx * i
            y = startY + dy * i
            touchDU(x, y)
        end
    end
end

function setOneItem(itemType, x, y)
    local postion = BUTTON_POSITIONS[itemType]
    if postion == nil then
        return
    end
    local itemButtonX, itemButtonY = postion[1], postion[2]

    if itemButtonX > 0 and itemButtonY > 0 then
        touchDU(itemButtonX, itemButtonY)
        touchDU(x, y)
    end
end

function setItem(itemType, count, x, y)
    local postion = BUTTON_POSITIONS[itemType]
    if postion == nil then
        return
    end
    local itemButtonX, itemButtonY = postion[1], postion[2]

    if itemButtonX > 0 and itemButtonY > 0 then
        touchDU(itemButtonX, itemButtonY)
        for i = 1, count do
            touchDU(x, y)
        end
    end
end

function setTroopsAt(area, troopType, count)
    local startX, startY, endX, endY, x, y = 0, 0, 0, 0, 0, 0
    if area == 0 then
        startX = sbattack_vars["set_troop_startX"]
        startY = sbattack_vars["set_troop_startY"]
        endX = sbattack_vars["set_troop_endX"]
        endY = sbattack_vars["set_troop_endY"]
    end
    setTroops(troopType, count, startX, startY, endX, endY)
end

function setAllTroops(tmpX, tmpY)
    for i = 1, 5 do
        if is_afterAttack() then
            return
        end
        local troopType = "other"..i
        if BUTTON_POSITIONS[troopType] ~= nil then
            setItem(troopType, 5, tmpX, tmpY)
        end
    end
end

function attack()
    local setTroopPointX, setTroopPointY = sbattack_vars["set_troop_pointX"], sbattack_vars["set_troop_pointY"]
    local setSpellPointX, setSpellPointY = sbattack_vars["set_spell_pointX"], sbattack_vars["set_spell_pointY"]

    shrink()
    moveUp()
    setItem("gaint", 16, setTroopPointX, setTroopPointY)
    setTroopsAt(0, "barbarian", 10)
    mSleep(1000)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)
    setTroopsAt(0, "archer", 15)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)
    setOneItem("castle", setTroopPointX, setTroopPointY)
    setOneItem("king", setTroopPointX, setTroopPointY)
    setOneItem("queen", setTroopPointX, setTroopPointY)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)

    setTroopsAt(0, "archer", 15)
    setTroopsAt(0, "barbarian", 10)

    setOneItem("ragespell", setSpellPointX, setSpellPointY)

    setTroopsAt(0, "goblin", 10)

    for i=1,5 do
        setItem("barbarian", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
        setItem("archer", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
        setItem("goblin", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
    end

    setOneItem("king", -1, -1)
    setOneItem("queen", -1, -1)

    for i=1,6 do
        setTroopsAt(0, "barbarian", 10)
        setTroopsAt(0, "archer", 10)
        setTroopsAt(0, "goblin", 10)
    end

    setAllTroops(setTroopPointX, setTroopPointY)
end

function sbAttack()
    setTroopButtonsPosition()
    -- attack()
end

-- --------------sbAttack---------------

initLog("test", 0)
sbAttack()
initLog("test", 0)
